<template>
	<div class="code">
		<div style="width:342px;margin-right:10px;" class="bg">
			<left-tree :data="data" :title="title" :keyId="'id'" :type="2" :isEdit2="isEdit" @importHandle="importHandle" :fieldList="[]" @reloadHandle="reloadHandle" @filterHandle="filterHandle" :searchData="searchData" :loading="loading" @nodeClick="nodeClick" @ok="getList" @remove="remove" ref="leftTree"></left-tree>
		</div>

		<div class="bg rightTable" v-loading="loading">
			<h3 class="code-title">
				{{leftTreeData.dirPath?leftTreeData.dirPath.replace(/\>/g,'/') :''}}
				<!-- <el-button @click="test">测试</el-button> -->
			</h3>

			<el-tabs v-model="activeName" type="card" @tab-click="handleClick1" :before-leave="beforeSwitch1">
				<el-tab-pane v-for="(item,index) of tabData" :label="item.name" :name="(index).toString()" :key="item.name">
					<span slot="label" v-if="item.id!=editId">{{item.name}}
						<svg-icon icon-class="edit" v-show="!tabEdit" style="color: #1890ff;" @click="handleEditTab(item)"></svg-icon>
						<!-- <svg-icon icon-class="tree-minus" v-show="!tabEdit" @click="handleDeleteTab(item)"></svg-icon> -->
						<el-popconfirm title="确认删除吗？" @confirm="handleDeleteTab(item)" v-show="!tabEdit">
							<svg-icon icon-class="tree-minus" style="color:#FF414A;margin-left:4px;" slot="reference"></svg-icon>
						</el-popconfirm>

					</span>
					<span slot="label" v-else>
						<el-input v-model="item.name" style="width:220px;margin-right:6px;" :ref="'tabs1'+item.id"></el-input>
						<svg-icon icon-class="yes-sl" @click="handleCloseTab(item)" style="font-size:22px;vertical-align:middle;color:#1890ff;"></svg-icon>
						<svg-icon icon-class="no-sl" @click="handleCancelTab(item)" style="font-size:22px;vertical-align:middle;color:#606266;"></svg-icon>
					</span>
					<!-- 二级标签 -->
					<el-tabs v-model="activeName2" @tab-click="handleClick2" class="tab2" :before-leave="beforeSwitch2" v-if="activeName==index">
						<el-tab-pane v-for="(item2,index2) of item.childrens" :label="item2.name" :name="item2.name" :key="index2">
							<!-- <el-button @click="deleteTree(item2.id)">---</el-button> -->
						</el-tab-pane>
						<el-tab-pane label="+" name="add"></el-tab-pane>
					</el-tabs>
				</el-tab-pane>
				<el-tab-pane label="+" name="add"></el-tab-pane>

			</el-tabs>

			<!-- form表单 -->
			<el-form label-width="110px" :rules="rules" ref="form" :model="form" v-show="showForm" style="padding:0 20px;">
				<el-form-item label="编码名称：" prop="name">
					<span style="color:#606266;" v-if="!isEdit">{{form.name}}</span>
					<el-input style="width:400px;" v-model="form.name" v-else></el-input>
				</el-form-item>
				<el-form-item label="编码版本：">
					<span style="color:#606266;" v-if="!isEdit">{{activeName2}}</span>
					<el-input style="width:250px;" v-model="activeName2" disabled v-else></el-input>
				</el-form-item>
				<el-form-item label="编码范围：" prop="scope">
					<span style="color:#606266;white-space:pre-wrap" v-if="!isEdit">{{form.scope}}</span>
					<el-input  type="textarea" v-model="form.scope" v-else></el-input>
				</el-form-item>
				<el-form-item label="编码示例：" prop="instance">
					<span style="color:#606266;white-space:pre-wrap" v-if="!isEdit">{{form.instance}}</span>
					<el-input  type="textarea" v-model="form.instance" v-else></el-input>
				</el-form-item>
				<el-form-item label="编码规则：" prop="rule">
					<span style="color:#606266;white-space:pre-wrap" v-if="!isEdit">{{form.rule}}</span>
					<el-input type="textarea" v-model="form.rule" v-else></el-input>
				</el-form-item>
				<el-form-item label="编码备注：" prop="remark">
					<span style="color:#606266;white-space:pre-wrap" v-if="!isEdit">{{form.remark}}</span>
					<el-input type="textarea" v-model="form.remark" v-else></el-input>
				</el-form-item>
				<el-form-item label="创建人：" v-if="!isAdd">
					<span style="color:#606266;" v-if="!isEdit">{{form.createName}}</span>
					<el-input style="width:400px;" v-model="form.createName" disabled v-else></el-input>
				</el-form-item>
				<el-form-item label="创建时间：" v-if="!isAdd">
					<span style="color:#606266;" v-if="!isEdit">{{form.createTime}}</span>
					<el-input style="width:400px;" v-model="form.createTime" disabled v-else></el-input>
				</el-form-item>
				<el-form-item label="更新人：" v-if="!isAdd">
					<span style="color:#606266;" v-if="!isEdit">{{form.updateName}}</span>
					<el-input style="width:400px;" v-model="form.updateName" disabled v-else></el-input>
				</el-form-item>
				<el-form-item label="更新时间：" v-if="!isAdd">
					<span style="color:#606266;" v-if="!isEdit">{{form.updateTime}}</span>
					<el-input style="width:400px;" v-model="form.updateTime" disabled v-else></el-input>
				</el-form-item>
				<div style="text-align:center;padding:16px 10px;">
					<el-button type="primary" @click="editForm" v-if="!isEdit" class="w96">编辑</el-button>
					<el-popconfirm title="确认删除吗？" @confirm="handleDelete" v-if="!isEdit">
						<el-button type="danger" class="w96" slot="reference" style="margin-left:10px;">删除</el-button>
					</el-popconfirm>
					<template v-if="isEdit">
						<el-button type="primary" @click="handleComfirm" class="w96">确定</el-button>
						<el-button @click="handleCancel" class="w96">取消</el-button>
					</template>
				</div>
			</el-form>
		</div>
	</div>
</template>

<script>
	import { standardTreeList, editStandardTree, removeStandardTree } from "@/api/dataManagement/standard/index";
	import { editDirectory, addDirectory, deleteDirectory, searchFindCode} from "@/api/dataManagement/standard/codeDirectory";
	import {uploadImportExcel } from "@/api/dataManagement/standard/dict";
	import leftTree from '../modules/leftTree.vue'
	export default {
		components: { leftTree },
		data() {
			return {
				title: '编码目录',
				loading: false,  //右边表单  loading
				keyword: '',
				//树形数据
				data: [],
				// 选中标签
				activeName: 0,
				activeName2: '',
				tabData: [
				],
				form: {},
				isEdit: false,
				editId: '',
				tabEdit: false,
				timer: null,//定时器
				// 树形选中项数据
				leftTreeData: {},
				isAdd: false,//是否添加表单
				showForm: false,//是否展示表单
				// 表单校验
				rules: {
					name: [
						{ required: true, message: "编码名称不能为空", trigger: "blur" }
					],
					scope: [
						{ required: true, message: "编码范围不能为空", trigger: "blur" }
					],
					instance: [
						{ required: true, message: "编码示例不能为空", trigger: "blur" }
					],
					rule: [
						{ required: true, message: "编码规则不能为空", trigger: "blur" }
					],
					remark: [
						{ required: true, message: "编码备注不能为空", trigger: "blur" }
					],
				},
				searchData:[
					{
						label:'按目录',
						value:'0'
					},
					{
						label:'按编码名',
						value:'1'
					}
				]
			}
		},
		created() {
			if (this.$route.query.id) {
				this.getList(1)
				this.getTabList()
			} else {
				this.getList()
			}
		},
		methods: {
			// 获取左侧树形数据
			getList(arg) {
				this.loading = true
				standardTreeList({ child_type: 0, type: 2 }).then(res => {
					if (res.code == 200) {
						this.data = [{ id: 'root', name: '编码目录', level: -1, type: 2, childrens: res.data }]
						this.$refs.leftTree.getMaxFloor(res.data)
						if (arg == 1) {
							this.$refs.leftTree.setHeightLight()
							this.$nextTick(() => {
								this.leftTreeData = this.$refs.leftTree.getCurrentNode()
							})
						}
					}
					this.loading = false
				}).catch(() => {
					this.loading = false
				})
			},
			// tab数据获取
			getTabList() {
				this.loading = true
				standardTreeList({ child_type: 1, type: 2, parent_id: this.$route.query.id }).then(res => {
					if (res.code == 200) {
						this.tabData = res.data
						this.$nextTick(() => {
							this.tabHieghtLight()
						})
					}
					// if (this.isAdd) {
					// 	this.isAdd = false
					// 	this.$nextTick(() => {
					// 		this.handleAdd()
					// 	})
					// }
					this.loading = false
				}).catch(() => {
					this.loading = false
				})
			},
			// 树形点击事件
			nodeClick(data) {
				if (this.isEdit || this.editId != '') {
					this.$message({
						type: 'warning',
						message: '请先保存修改！'
					})
					this.$refs.leftTree.setHeightLight()
					return false
				}
				if (data.id == 'root' && this.$route.query.id) {
					this.$refs.leftTree.setHeightLight()
				}
				else if (data.id != 'root' && this.$route.query.id != data.id) {
					this.$router.push({ query: { id: data.id } })
					this.leftTreeData = data
					this.getTabList()
					this.activeName = "0"
				}
			},
			// 导入
			importHandle(data){
					// 1：数据字典，2：编码目录，3：行业概念）
				uploadImportExcel(2,data).then(res=>{
					this.$message({
						type: 'success',
						message: '导入编码目录成功'
					})
					this.getList(1)
				})
			},
			/** tab事件 */
			handleClick1(data) {
				if (data.label == '+') {
					return false
				}
				this.tabHieghtLight()
			},
			handleClick2(component, type) {
				if (component.label != '+') {
					this.handleGetForm()
				}
			},
			// tab2级高亮
			tabHieghtLight() {
				if (!this.tabData[this.activeName] || this.isEdit || this.editId != '') {
				}
				else if (this.tabData[this.activeName].childrens && this.tabData[this.activeName].childrens.length > 0) {
					this.activeName2 = this.tabData[this.activeName].childrens[0].name
					this.$nextTick(() => {
						this.handleGetForm()
					})
				}
				if (this.tabData.length > 0 && this.tabData[this.activeName] && this.tabData[this.activeName].childrens && this.tabData[this.activeName].childrens.length > 0) {
					this.showForm = true
				} else {
					this.showForm = false
				}
			},
			beforeSwitch1(activeName) {
				if (this.tabEdit) {
					// this.editing()
					return false
				}
				if (this.isEdit) {
					this.editing()
					return false
				}
				if (activeName == 'add') {
					this.addTabs1()
					return false
				}
			},
			beforeSwitch2(activeName) {
				if (this.tabEdit) {
					// this.editing()
					return false
				}
				if (this.isEdit) {
					this.editing()
					return false
				}
				if (activeName == 'add') {
					this.addTabs2()
					return false
				}
			},
			addTabs1() {
				if (!this.$route.query.id) {
					this.$message.warning('请选中一项！')
					return false
				}
				let params = {
					id: Math.ceil(Math.random() * 1000000), name: '', level: this.leftTreeData.level + 1, parentId: this.leftTreeData.id, type: this.leftTreeData.type, childType: 1, isAdd: true
				}
				this.editId = params.id
				this.tabData.push(params)
				this.handleEditTab(params)

				this.form = {}
				// this.activeName = '3'
			},
			addTabs2() {
				this.showForm = true
				this.form = {}
				let record = this.tabData[this.activeName]
				let str = ''
				if(record.childrens.length>0){
					str = record.childrens[record.childrens.length - 1].name
				}else{
					str = 'v0'
				}
				let params = {
					name: 'v' + (Number(str.substring(1, str.length)) + 1),
					level: record.level + 1, parentId: record.id, type: record.type, childType: 1,
				}
				this.tabData[this.activeName].childrens.push(params)
				// this.handleCloseTab2(params)
				this.activeName2 = params.name
				this.$nextTick(() => {
					this.isEdit = true
					this.isAdd = true
				})
			},
			// 一级tab编辑事件
			handleEditTab(data) {
				this.tabEdit = true
				this.editId = data.id
				setTimeout(() => {
					this.$refs['tabs1' + data.id][0].focus()
				}, 300)
				console.log("data:", data)
			},

			handleCloseTab(data) {
				console.log("数据：", data)
				if (data.name == '') {
					this.$message.error('不能为空');
					return false
				}
				let param = { childType: 1, id: data.id, level: data.level, name: data.name, parentId: data.parentId, type: data.type,sort:0 }
				if (data.isAdd) {
					delete param.id
				}
				this.loading = true
				editStandardTree(param).then(res => {
					if (res.code == 200) {
						this.tabEdit = false
						this.editId = ''
						this.getTabList()
					}
					this.loading = false
				}).catch(err => {
					this.loading = false
				})
				this.editId = ''
			},
			handleCancelTab(data) {
				console.log("data:", data)
				this.tabEdit = false
				this.editId = ''
				this.getTabList()
				// if (data.isAdd) {
				// 	return false
				// }
				// removeStandardTree({ id: data.id }).then(res => {
				// 	if (res.code == 200) {
				// 		this.$message({
				// 			type: 'success',
				// 			message: res.msg
				// 		})
				// 		this.getTabList()
				// 	}
				// 	this.loading = false
				// }).catch(() => { this.loading = false })
			},
			handleDeleteTab(data) {
				removeStandardTree({ id: data.id }).then(res => {
					if (res.code == 200) {
						this.$message({
							type: 'success',
							message: res.msg
						})
						this.getTabList()
					}
					this.loading = false
				}).catch(() => { this.loading = false })
			},
			handleCloseTab2(params) {
				this.handleAdd(params)
				// this.loading = true
				// editStandardTree(params).then(res => {
				// 	if (res.code == 200) {
				// 		this.editId = ''
				// 		this.getTabList()
				// 	}
				// 	this.loading = false
				// }).catch(err => {
				// 	this.loading = false
				// })
			},
			// 编辑中提示
			editing() {
				if (this.timer) {
					return false
				}
				this.$message({
					showClose: true,
					message: '编辑中，请先保存！',
					type: 'warning'
				});
				this.timer = setTimeout(() => {
					clearTimeout(this.timer)
					this.timer = null
				}, 30)
			},
			/** 表单事件 */
			handleGetForm(id) {
				let versionId
				if (id) {
					versionId = id
				} else {
					versionId = this.tabData[this.activeName].childrens.filter(item => { return item.name == this.activeName2 })[0].id
				}
				if (this.loading) return false
				this.loading = true
				editDirectory(versionId).then(res => {
					if (res.code == 200) {
						if (!res.data) {
							this.form = {}
						} else {
							this.form = res.data
						}
					}
					this.loading = false
				}).catch(() => { this.loading = false })
			},
			editForm(data) {
				this.isEdit = true
			},
			handleComfirm() {
				this.$refs["form"].validate(valid => {
					if (valid) {
						if (this.isAdd) {
							this.handleCloseTab2(this.tabData[this.activeName].childrens[this.tabData[this.activeName].childrens.length - 1])
						} else {
							this.handleSave()
						}
					}
				})
			},
			handleAdd(record) {
				// return false
				// // let versionId = this.tabData[this.activeName].childrens.filter(item => { return item.name == this.activeName2 })[0].id
				// // if (!versionId) {
				// // 	this.$message.error('添加失败')
				// // }
				let params = {
					version: {
						...record
					},
					...this.form,
				}

				if (this.loading) return false
				this.loading = true

				addDirectory(params).then(res => {
					if (res.code == 200) {
						this.$message({
							type: 'success',
							message: res.msg
						})

						this.loading = false
						this.isEdit = false
						this.$refs.leftTree.setHeightLight()
						// this.getTabList()
						record.id = res.data
						this.handleGetForm(res.data)
					}
					this.loading = false
				}).catch(() => { this.loading = false })
			},
			handleSave(data) {
				let params = {
					...this.form,
				}
				if (this.loading) return false
				this.loading = true
				addDirectory(params).then(res => {
					if (res.code == 200) {
						this.$message({
							type: 'success',
							message: res.msg
						})
						this.handleGetForm()
						this.isEdit = false
						this.$refs.leftTree.setHeightLight()
					}
					this.loading = false
				}).catch(() => { this.loading = false })
			},
			handleCancel(data) {
				this.$refs.form.resetFields() //移除校验结果
				this.getTabList()
				this.handleGetForm()
				this.isEdit = false
				this.isAdd = false
			},
			handleDelete() {
				console.log("data:", this.form)
				if (this.loading) return false
				this.loading = true
				deleteDirectory(this.form.id).then(res => {
					if (res.code == 200) {
						removeStandardTree({ id: this.form.versionId }).then(res => {
							if (res.code == 200) {
								this.$message({
									type: 'success',
									message: res.msg
								})
								this.getTabList()
							}
							this.loading = false
						}).catch(() => { this.loading = false })
					}
				}).catch(() => { this.loading = false })
			},
			remove() {
				this.leftTreeData = {}
			},
			test() {
				console.log("activeName：", this.activeName)
				console.log("activeName2：", this.activeName2)
				console.log("222：", this.tabData)
				console.log("showForm：", this.showForm)
			},
			// 测试使用删除
			deleteTree(id) {
				removeStandardTree({ id: id }).then(res => {
					if (res.code == 200) {
						this.$message({
							message: '删除成功',
							type: 'success'
						});
					}
				})
			},
			// 按字段搜索
			filterHandle(keyword){
				// keyword = 156;
				var that =  this;
				// var data = that.data
				// var arrList= '';
				// let route = [];
				var successData = []
				this.loading =  true;
				searchFindCode({directoryName :keyword}).then(res=>{
					if (res.code == 200) {
						var dataList = getList(res.data);
						getList(dataList)
						this.data = dataList.length>0?[{ id: 'root', name: '编码目录', level: -1, type: 2, childrens: dataList }] :[]
						this.$refs.leftTree.getMaxFloor(dataList)
						this.$refs.leftTree.setHeightLight()
						this.$nextTick(() => {
							this.leftTreeData = this.$refs.leftTree.getCurrentNode()
						})
						this.loading =  false;
					}
				})
				function getList (data){
					var tmpData=data;
					for(var i=0;i<tmpData.length;i++){
						if(tmpData[i].childType == 1) {
							tmpData[i] = '';
						} else {
							tmpData[i].childrens = tmpData[i].childrens.filter(Boolean)
							getList (tmpData[i].childrens)
						}
					}
					return tmpData;
				};

			},
			reloadHandle(type){
				if(type!='按目录') {
					this.data = [];
					return;
				}
				this.getList(1)
			}
		}
	}
</script>

<style lang="scss" scoped>
	@import "~@/assets/styles/system/common.scss";
	.code {
		margin: 0px 0px 30px 0px;
		padding: 0 10px;
		min-width: 1000px;
		display: flex;
		min-height: calc(100vh - 124px);
		.bg {
			background: #ffffff;
			padding: 20px 16px;
		}
		::v-deep.el-tree {
			.el-tree-node__content {
				height: 28 px;
			}
		}
		.tree-header {
			padding-bottom: 16px;
			border-bottom: 1px solid #f0f0f0;
			.code-title {
				border-left: 4px solid #1183f8;
				padding-left: 10px;
				line-height: 20px;
				height: 20px;
				font-weight: 400;
				font-size: 18px;
				margin: 0 0 20px 0;
			}
		}
		.tree-content {
			padding: 14px 0px;
			::v-deep.el-tree {
				.el-tree-node__label {
					font-size: 16px;
					font-weight: 400;
					color: #1e1e1e;
					line-height: 28px;
				}
			}
		}
		.code-title {
			border-left: 4px solid #1183f8;
			padding-left: 10px;
			line-height: 20px;
			height: 20px;
			font-weight: 500;
			font-size: 18px;
			margin: 0 0 20px 0;
			color: #606266;
		}

		// padding: 0 20px;
		::v-deep.el-tabs.tab2 {
			.el-tabs__item {
				min-width: 72px;
				text-align: center;
				padding: 0;
			}
		}
		.w96 {
			width: 96px;
		}
		.rightTable {
			width: calc(100% - 352px);
		}
	}
</style>